package gui;

import game.GameManager;
import game.GameState;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import network.GameFinder;
import network.GameInfo;
import network.PlayerJoined;
import network.Receiver;


@SuppressWarnings("serial")
public class GameSelectionPanel extends JPanel implements ActionListener,PlayerJoined {
	private JButton createGame,cancel,start,refresh, join;
	private JTextArea joinedPlayers;
	private String playerName;
	private JComboBox gameSelector;
	private ArrayList<GameInfo> availableGames;
	private ArrayList<String> ips;
	private GameManager waitingManager;
	private GameState waitingGame;
	private Receiver listener;
	private int playerNum;
	public GameSelectionPanel(){
		super();
		while (playerName == null || playerName.equals(""))
			playerName = JOptionPane.showInputDialog ( "Enter your username:");
		
		initialGUI();
	}
	public void initialGUI(){
		this.removeAll();
		revalidate();
		repaint();
		setBackground(Color.white);
		BoxLayout b = new BoxLayout(this,BoxLayout.X_AXIS);
		setLayout(b);
		createGame = new JButton("Create Game");
		createGame.setAlignmentY(CENTER_ALIGNMENT);
		add(createGame);
		createGame.addActionListener(this);
		availableGames = GameFinder.findGames();
		String[] gameNames = new String[availableGames.size()];
		for (int i = 0; i < availableGames.size(); i++){
			gameNames[i] = availableGames.get(i).getName();
		}
		gameSelector = new JComboBox(gameNames);
		//gameSelector.setSelectedIndex(0);
		gameSelector.addActionListener(this);
		gameSelector.setAlignmentY(CENTER_ALIGNMENT);
		add(gameSelector);
		refresh = new JButton("Refresh");
		refresh.addActionListener(this);
		add(refresh);
		join = new JButton("Join");
		join.addActionListener(this);
		if (gameNames.length == 0){
			join.setEnabled(false);
		}
		add(join);
	}
	public void hostLayout(){
		initialGUI();
		remove(gameSelector);
		remove(refresh);
		remove(join);
		createGame.setEnabled(false);
		joinedPlayers = new JTextArea(waitingGame.getPlayerList());
		joinedPlayers.setMaximumSize(new Dimension(100,100));
		joinedPlayers.setEditable(false);
		add(joinedPlayers);
		cancel = new JButton("Cancel");
		cancel.addActionListener(this);
		add(cancel);
		start = new JButton("Start");
		start.addActionListener(this);
		add(start);
		revalidate();
		
	}
	public void joinerLayout(){
		removeAll();
		repaint();
		JLabel mess = new JLabel("Waiting on host to start");
		add(mess);
		setBackground(Color.white);
		revalidate();
		repaint();
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == createGame){
			playerNum = 0;
			waitingGame = new GameState();
			
			waitingGame.addPlayer(playerName);
			ips = new ArrayList<String>();
			waitingManager = new GameManager(waitingGame,ips,playerNum);
			Socket s;
			try {
				s = new Socket("google.com", 80);
				ips.add(s.getLocalAddress().getHostAddress());
			} catch (UnknownHostException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			if (listener != null){
				listener.closeListener();
			}
			try {
				listener = new Receiver(this,waitingManager);
				listener.makeHost(true,playerName);
				Thread detatch = new Thread(){
					@Override
					public void run(){
						try {
							System.out.println("listener started");
							listener.listen();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				};
				detatch.start();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			hostLayout();
			
			
		}
		else if (e.getSource() == cancel){
			initialGUI();
		}
		else if (e.getSource() == start){
			if (ips.size() > 1){
				waitingManager.startGame();
				GamePlayPanel newGame = new GamePlayPanel(waitingManager);
			}
		}
		else if (e.getSource() == refresh){
			initialGUI();
		}
		else if (e.getSource() == join){
			if (availableGames.size() > 0){
				int selectionIdx = gameSelector.getSelectedIndex();
				GameInfo join = availableGames.get(selectionIdx);
				
				playerNum = GameFinder.joinGame(join,playerName);
				waitingGame = new GameState();
				
				waitingGame.addPlayer(playerName);
				ips = new ArrayList<String>();
				waitingManager = new GameManager(waitingGame,ips,playerNum);
				if (listener != null){
					listener.closeListener();
				}
				try {
					listener = new Receiver(this,waitingManager);
					Thread detatch = new Thread(){
						@Override
						public void run(){
							try {
								System.out.println("listener started");
								listener.listen();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					};
					detatch.start();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				joinerLayout();
			}
		}
	}
	@Override
	public void playerJoined() {

		hostLayout();
	}
}
